//
//  SceneManager.m
//  AppleCilent
//
//  Created by Nail Sharipov on 02/04/14.
//  Copyright (c) 2014 Nail Sharipov. All rights reserved.
//

#import "SceneManager.h"
#import "AppDelegate.h"

@implementation SceneManager

+ (SceneManager*)getInstance
{
    static SceneManager* instance;
    
    @synchronized(self)
    {
        if (!instance)
            instance = [[SceneManager alloc] init];
        
        return instance;
    }
}

- (id)init
{
    self = [super init];
    sceneLinks = [[NSMutableDictionary alloc] init];
    return self;
}


- (UIViewController*)getCurrentScene
{
    return currentScene;
}
- (UIViewController*)getScene:(NSString*)sceneName
{
    UIViewController* scene = nil;
    scene = [sceneLinks objectForKey:sceneName];
    if (scene == nil) {
        UIStoryboard *storyboard = [[AppDelegate getInstance] getStoryboard];
        scene = [storyboard instantiateViewControllerWithIdentifier:sceneName];
        [sceneLinks setObject:scene forKey:sceneName];
    }
    return scene;
}

- (UIViewController*)openScene:(NSString*)sceneName
{
    UIWindow* window = [AppDelegate getInstance].window;
    
    UINavigationController* navigation = (UINavigationController*)[window rootViewController];
    UIViewController* newScene = [self getScene:sceneName];
    currentScene = newScene;
    
    NSArray* controllers = [navigation viewControllers];
    for (UIViewController* vc in controllers) {
        if (newScene == vc) {
            [navigation popToViewController:newScene animated:YES];
            return currentScene;
        }
    }

    [navigation pushViewController:newScene animated:YES];
    
    return currentScene;
}

- (UIViewController*)openEmbeddedScene:(UINavigationController*)navigation sceneName:(NSString*)sceneName
{
    UIViewController* topViewController = [navigation topViewController];
    
    UIViewController* newScene = [self getScene:sceneName];

    

    
    
    
    if (topViewController != newScene) {
//        popViewControllerAnimated
        [navigation pushViewController:newScene animated:YES];
    }
    return newScene;
}

- (UIViewController*)openEmbeddedSceneByName:(NSString*)navigationName sceneName:(NSString*)sceneName
{
    UINavigationController* navigation = (UINavigationController*)[self getScene:navigationName];
    return [self openEmbeddedScene:navigation sceneName:sceneName];
}

@end
